﻿using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc;
using Project.Net.Domain.Log;
using Project.Net.ResponseModel;
using Project.Net.Domain.Ex;

namespace Project.Net.Filters
{
    /// <summary>
    /// 全局异常过滤器
    /// </summary>
    public class GlobalExceptionFilter : IExceptionFilter
    {
        private readonly ILoggerService _logger;

        public GlobalExceptionFilter( ILoggerService logger )
        { 
            _logger = logger;
        }

        public void OnException(ExceptionContext context)
        {
            if (context.Exception is DomainException ex)
            {
                // 捕获领域层/应用层抛出的异常
                context.Result = new JsonResult(ApiResponse<object>.Fail(ex.Code, ex.Message));
                context.HttpContext.Response.StatusCode = 400; // BadRequest
            }
            else
            {
                // 系统级异常处理
                context.Result = new JsonResult(ApiResponse<object>.Fail(CodeEnums.服务错误, "系统错误"));
                context.HttpContext.Response.StatusCode = 500;
                _logger.LogError(context.Exception.Message, context.Exception.InnerException ?? context.Exception);

            }
            context.ExceptionHandled = true;
        }
    }

}
